package com.example.myproject.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;

import java.io.IOException;

/**
 * Created by xi on 2018/9/24.
 */
public class JacksonStringDeserializer extends StdScalarDeserializer<String> {
    private static final long serialVersionUID = -180126462059654064L;

    public JacksonStringDeserializer() {
        super(String.class);
    }

    protected JacksonStringDeserializer(Class<?> vc) {
        super(String.class);
    }
    public boolean isCachable() {
        return true;
    }

    public Object getEmptyValue(DeserializationContext ctxt) throws JsonMappingException {
        return "";
    }

    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        if(p.hasToken(JsonToken.VALUE_STRING)) {
            return p.getText().trim();
        } else {
            JsonToken t = p.getCurrentToken();
            if(t == JsonToken.START_ARRAY) {
                return (String)this._deserializeFromArray(p, ctxt);
            } else if(t == JsonToken.VALUE_EMBEDDED_OBJECT) {
                Object text1 = p.getEmbeddedObject();
                return text1 == null?null:(text1 instanceof byte[]?ctxt.getBase64Variant().encode((byte[])((byte[])text1), false):text1.toString().trim());
            } else {
                String text = p.getValueAsString().trim();
                return text != null?text:(String)ctxt.handleUnexpectedToken(this._valueClass, p);
            }
        }
    }

    public String deserializeWithType(JsonParser p, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException {
        return this.deserialize(p, ctxt);
    }
}
